package com.jf.cloud.multishop.feign;

import com.alibaba.fastjson.JSON;
import com.jf.cloud.api.multishop.feign.WalletLogOperationFeignClient;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.order.feign.OrderFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.bo.EsOrderBO;
import com.jf.cloud.common.order.bo.PayNotifyBO;
import com.jf.cloud.common.order.vo.OrderSimpleAmountInfoBO;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.vo.ShopSubstituteSalesVO;
import com.jf.cloud.multishop.service.ShopSubstituteSalesService;
import com.jf.cloud.multishop.service.ShopWalletService;
import com.jf.cloud.multishop.service.WalletLogOperationService;
import com.jf.cloud.multishop.vo.ShopWalletVO;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chiley
 * @date 2022/6/30 16:55
 */
@RestController
@Hidden
public class WalletLogOperationFeignController implements WalletLogOperationFeignClient {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private WalletLogOperationService walletLogOperationService;
    @Autowired
    private ShopWalletService shopWalletService;
    @Autowired
    private ShopSubstituteSalesService shopSubstituteSalesService;

    @Override
    public ServerResponseEntity<Void> addSupplierLog(String st) {
        List<EsOrderBO> orderBOList = JSON.parseArray(st, EsOrderBO.class);
        Set<Long> shopIds = orderBOList.stream().map(EsOrderBO::getShopId).collect(Collectors.toSet());
        // 根据shopIds获取商家的代销配置
        List<ShopSubstituteSalesVO> shopSubstituteSalesList = shopSubstituteSalesService.listByShopIds(new ArrayList<>(shopIds));
        Map<Long, Integer> salesMap = shopSubstituteSalesList.stream().collect(Collectors.toMap(ShopSubstituteSalesVO::getShopId, ShopSubstituteSalesVO::getOrderShape));

        for (EsOrderBO esOrderBO : orderBOList) {
            try {
                PayNotifyBO message = new PayNotifyBO();
                message.setPreSaleType(message.getPreSaleType());
                message.setOrderIds(Collections.singletonList(esOrderBO.getOrderId()));
                // 添加未结算记录
                // 采购订单不分账
                if (Objects.equals(message.getPurchaseOrder(), Boolean.TRUE)) {
                    continue;
                }
                // 定金预售订单付定金时不用全部分账
                boolean isPreSale = Objects.nonNull(message.getPreSaleType()) && Objects.equals(message.getPreSaleType(), PreSaleType.DEPOSIT.value())
                        && Objects.equals(message.getOrderStatus(), OrderStatus.UNPAY.value());
                if (isPreSale) {
                    continue;
                }
//            LOG.info("订单支付成功，分账... message: " + Json.toJsonString(message));

                ServerResponseEntity<List<OrderSimpleAmountInfoBO>> ordersShopWalletInfoResponse = orderFeignClient.getOrdersSimpleAmountInfo(message.getOrderIds());
                if (!ordersShopWalletInfoResponse.isSuccess()) {
                    throw new LuckException(ResponseEnum.EXCEPTION);
                }
                List<OrderSimpleAmountInfoBO> orderShopWalletInfos = ordersShopWalletInfoResponse.getData();
                // 获取店铺已结算金额map
                List<ShopWalletVO> shopWalletList = shopWalletService.listByShopIds(new ArrayList<>(shopIds));
                Map<Long, Long> settledAmountMap = shopWalletList.stream().collect(Collectors.toMap(ShopWalletVO::getShopId, ShopWalletVO::getSettledAmount));
                // 筛选掉需要采购和采购完成的
                orderShopWalletInfos = orderShopWalletInfos.stream().filter(orderSimpleAmountInfoBO -> Objects.equals(orderSimpleAmountInfoBO.getWaitPurchase(), 0)).collect(Collectors.toList());
                message.setAgreePurchase(1);
                walletLogOperationService.addAmountByOrder(orderShopWalletInfos, message, settledAmountMap, salesMap);


                // ============================================已结算记录============================================

                if (Objects.equals(esOrderBO.getIsSettled(), 1)) {
                    walletLogOperationService.addAmountBySettledOrder(esOrderBO.getOrderId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return ServerResponseEntity.success();
    }

}